/*
 * @Author: wwssaabb
 * @Date: 2021-07-26 16:02:23
 * @LastEditTime: 2021-08-13 18:08:18
 * @FilePath: \react-admin-server\App.js
 */

const koa=require('koa')
const path=require('path')
const fs=require('fs')
const cors=require('koa2-cors')
const static=require('koa-static')
const koaBody=require('koa-body')

const app=new koa()

//允许跨域
app.use(cors())

//解析body
app.use(koaBody({
  multipart:true, 
  formidable:{
    uploadDir:path.join(__dirname,'/public/upload/'),
    maxFileSize:200*1024*1024,//限制文件上传大小限制
    keepExtensions:true,//保持文件上传的后缀名
    multipart:true,
  }
}))

//暴露静态资源文件夹public
app.use(static(path.join(__dirname+'/public')))
//连接数据库
require(__dirname+'/model/connect')

//注册整合的路由
require(__dirname+'/router/index')(app)

//解决前端Browser路由刷新时not found的问题
app.use(async (ctx,next)=>{
  console.log(ctx.request.url)
  let index=fs.readFileSync(__dirname+'/public/index.html','utf-8')
  if(index){
    ctx.status=200
    ctx.body=index
  }else{
    ctx.status=500
    ctx.body='<h2>Backend Error<h2>'
  }
})

app.listen(3333,err=>{
  if(!err){
    console.log('服务器开启成功!,访问后台管理页面 http://localhost:3333/home')
  }else{
    console.log('服务器开启失败!',err)
  }
})